#!/usr/bin/env  python
# encoding: utf-8
'''
Utils.JsonHelper -- Json helper

Utils.JsonHelper is a set of methods used by json loads and dumps

It defines classes_and_methods

@author:     Anson Chan

@copyright:  2016 Xerland Co. Ltd. All rights reserved.

@contact:    anson_chan@xerland.com
@deffield    updated: Updated
'''
import sys
from Adb.MachModel import MachModel
def toJson(obj):
#    d = {'__class__':obj.__class__.__name__,
#         '__module__':obj.__module__}
#    d.update(obj.__dict__)
    d =obj.__dict__
    return d
    
def fromJson(d):
    inst = d
    if '__class__' in d:
        class_name = d.pop('__class__')
        module_name = d.pop('__module__')
#        print module_name
        module = __import__(module_name, fromlist=[class_name])
#        print 'MODULE:', module
        class_ = getattr(module, class_name)
#        print 'CLASS:', class_
        args = dict( (key.encode('ascii'), value) for key, value in d.items())
#        print 'INSTANCE ARGS:', args
        inst = class_(**args)
    else:
        if set(d.keys()) == set(["mMachID","mMachName","mPowerOnTime","mPowerOffTime"]):
            args = dict( (key.encode('ascii'), value) for key, value in d.items())
            inst = MachModel(**args)
    return inst

if __name__ == '__main__':
    d = """{"mMachID":1, "mMachName":"1-设备名称", "mPowerOnTime":"2016-8-5 14:01:12", "mPowerOffTime":"2016-8-5 14:37:04"}"""
    mach = fromJson(eval(d))
    print mach,mach.mMachID
